<?php namespace Common\Model;
use Hdphp\Model\Model;
/**
 * 商品模型
 */
class Goods extends Model {
	protected $tables='Goods';
	protected $validate=array(
		array('gname','required','标题不能为空',3,3),
		array('category_cid','required','必须选择分类',3,3),
		);
	protected $auto=array(
        array('shtime','time','function',3,1),
    );
   public function store()
   {
   	$goodscont= new \Common\Model\GoodsCont;	
   	if(!$this->create()) return false;
	if(!$goodscont->create()){
		$this->error = $goodscont->getError();
		return false;
	}
	$this->data['user_uid']=$_SESSION['uid'];
	$gid=$this->add();
	$goodscont->data['goods_gid']=$gid;
	$photo=implode('|',$_POST['photo']);
	$goodscont->data['photo']=$photo;
	$goodscont->add();
	return $gid;
   }
   public function del($gid){
		(new \Common\Model\GoodsAtt)->where("goods_gid={$gid}")->delete();
		(new \Common\Model\GoodsCont)->where("goods_gid={$gid}")->delete();
		$this->delete($gid);
	}
   public function edit($gid)
   {
   	$goodscont= new \Common\Model\GoodsCont;	
   	if(!$this->create()) return false;
	if(!$goodscont->create()){
		$this->error = $goodscont->getError();
		return false;
	}
		(new \Common\Model\GoodsAtt)->where("goods_gid={$gid}")->delete();
			foreach (Q('post.attr',array()) as $taid => $value) {
				if($value){
					$data = array(
						'gavalue' => $value,
						'type_att_taid' => $taid,
						'goods_gid' =>$gid,
					);
					$model = new \Common\Model\GoodsAtt;
					$model->add($data);
				}
			}
			//循环商品规格插入goods_attr
			foreach (Q('post.spec',array()) as $key => $value) {
				if($value){
					foreach ($value['value'] as $k => $v) {
						$data = array(
						'gavalue' =>$value['value'][$k],
						'type_att_taid' => $key,
						'gprice'=>$value['price'][$k],
						'goods_gid' => $gid,
					);
					$model = new \Common\Model\GoodsAtt;
					$model->add($data);
					}
				}
			}
	$this->where("gid={$gid}")->save();
	$photo=implode('|',$_POST['photo']);
	$goodscont->data['photo']=$photo;
	$goodscont->where("goods_gid={$gid}")->save();
	return true;
   }
   
}
?>